package com.landiao.ctrler.management;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.weixin.WxConsts;
import com.landiao.common.weixin.WxErrorException;
import com.landiao.common.weixin.WxMpService;
import com.landiao.common.weixin.bean.WxMpMassGroupMessage;
import com.landiao.common.weixin.bean.WxMpMassNews;
import com.landiao.common.weixin.bean.WxMpMassNews.WxMpMassNewsArticle;
import com.landiao.common.weixin.bean.WxMpMassSendResult;
import com.landiao.common.weixin.bean.WxMpMassUploadResult;
import com.landiao.ctrler.BaseCRUDCtrler;
import com.landiao.entities.Coupon;
import com.landiao.entities.Material;
import com.landiao.service.CouponService;
import com.landiao.service.CouponShopRelaService;
import com.landiao.service.MaterialService;

@Controller
@RequestMapping("/management/coupon")
public class CouponCtrler extends BaseCRUDCtrler<Coupon, String>  {
	
	private static final String COUPON_RECEIVE_URL = "weixin/vip/coupon/receive/";
	
	@Autowired
	private CouponShopRelaService couponShopRelaService;
	
	@Autowired
	private MaterialService materialService;
	
	@Autowired
	@Qualifier("vipWxService")
	private WxMpService vipWxService;
	
	private CouponService getCouponService() {
        return (CouponService) baseService;
    }

	@Override
	public String save(Coupon t, RedirectAttributes redirectAttr) {
		// TODO Auto-generated method stub
		t.setCompId(this.getClientUser().getUser().getCompId());
		getCouponService().save(t);
		redirectAttr.addFlashAttribute("resultMsg",
				ResultMsgFactory.success("添加成功"));
		return redirectToUrl(viewName("index"));
	}

	@Override
	public String update(Coupon t, RedirectAttributes redirectAttr) {
		// TODO Auto-generated method stub
		try{
			t.setCompId(this.getClientUser().getUser().getCompId());
			getCouponService().update(t);
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.success("修改成功"));
		}catch(Exception e){
			e.printStackTrace();
			log.error("修改失败：{}",e.getMessage());
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.fail("修改失败"));
		}
		return redirectToUrl(viewName("index"));
	}

	@Override
	public ResultMsg delete(@PathVariable String id) {
		// TODO Auto-generated method stub
		System.out.println(id);
		//先删除关联的门店信息
		couponShopRelaService.deleteByCouponId(id);
		return super.delete(id);
	}
	@ResponseBody
	@RequestMapping(value = "out/{id}", method = RequestMethod.POST)
	public ResultMsg out(@PathVariable String id) {
		try{
			Coupon coupon = this.baseService.getById(id);
			if(coupon==null){
				return ResultMsgFactory.fail("发放失败");
			}
			if(coupon.getMaterialId()==null){
				return ResultMsgFactory.fail("请先选择素材");
			}
			
			if(StringUtils.isEmpty(coupon.getMediaId())){
				Material material = this.materialService.getById(coupon.getMaterialId());
				
				WxMpMassNewsArticle article = new WxMpMassNewsArticle();
				article.setContent(material.getContent());
				article.setThumb_media_id(material.getMediaId());
				article.setTitle(material.getTitle());
				article.setContent_source_url(this.webSite+COUPON_RECEIVE_URL+id);
				article.setDigest(material.getSummary());//添加摘要
				WxMpMassNews news = new WxMpMassNews();
				news.addArticle(article);
				
				//先上传图文消息
				WxMpMassUploadResult wuResult = vipWxService.massNewsUpload(news);
				//更新coupon表中的media_id
				coupon.setMediaId(wuResult.getMedia_id());
			}
			if(StringUtils.isNotEmpty(coupon.getMediaId())){
				ResultMsg resultMsg = null;
				WxMpMassGroupMessage message = new WxMpMassGroupMessage();
				message.setMediaId(coupon.getMediaId());
				message.setMsgtype(WxConsts.MASS_MSG_NEWS);
				log.debug(message.toJson());

				try{
					//群发消息
					WxMpMassSendResult result = vipWxService.massGroupMessageSend(message);
					if(result.getErrcode().equals("0")){
						coupon.setMsgId(result.getMsg_id());
						coupon.setState("10A");
						resultMsg = ResultMsgFactory.success("发放成功");
					}else if(result.getErrcode().equals("45028")){
						resultMsg = ResultMsgFactory.fail("当月微信群发次数已达4次，不能再群发");
					}else{
						resultMsg = ResultMsgFactory.fail("微信发放失败");
					}
				}catch(WxErrorException e){
					if(e.getError().getErrcode()==45028)
						resultMsg = ResultMsgFactory.fail("当月微信群发次数已达4次，不能再群发");
					else
						resultMsg = ResultMsgFactory.fail("微信发放失败,错误码："+e.getError().getErrcode());
				}catch(Exception e){
					resultMsg = ResultMsgFactory.fail("微信发放失败");
				}
				this.baseService.update(coupon);
				return resultMsg;
			}else{
				return ResultMsgFactory.fail("微信发放失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("发放失败：{}",e.getMessage());
			return ResultMsgFactory.fail("发放失败");
		}
	}

	@Override
	public String edit(Model model, @PathVariable String id) {
		// TODO Auto-generated method stub
		Coupon t = getCouponService().getById(id);
		//通过couponId查询关联的门店并组成字符串 如："a1,a2,a3"
		String shops = couponShopRelaService.getShopIdsByCouponId(id);
		model.addAttribute("t",t);
		model.addAttribute("shops",shops);
		return viewName("edit");
	}
	@RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
	public String detail(Model model,@PathVariable String id) {
		Coupon t = getCouponService().getById(id);
		//通过couponId查询关联的门店并组成字符串 如："a1,a2,a3"
		String shops = couponShopRelaService.getShopIdsByCouponId(id);
		model.addAttribute("t",t);
		model.addAttribute("shops",shops);
		return viewName("detail");
	}
}
